﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using seejee_Backendium.Core.Interfaces;
using seejee_Backendium.Core.Models;

namespace seejee_Backendium.Data.Services
{
    public class BILogenAccListService:IBILogenAccListService
    {
        private readonly string _connectionString;
        private readonly ILogger<BILogenAccListService> _logger;

        public BILogenAccListService(IConfiguration config, ILogger<BILogenAccListService> logger)
        {
            _connectionString = config.GetConnectionString("Default");
            _logger = logger;
        }

        public async Task<IEnumerable<DataSourcesDto>> GetAllAccListAsync(string cOperatorName)
        {
            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();

            try
            {
                // 1. 首先查询 iCusDBPermissions 字段
                var permissionsJson = await connection.QueryFirstOrDefaultAsync<string>(
                    "SELECT iCusDBPermissions FROM SEBI_Operator WHERE cOperatorName = @cOperatorName",
                    new { cOperatorName });

                if (string.IsNullOrEmpty(permissionsJson))
                    return Enumerable.Empty<DataSourcesDto>();

                // 2. 解析 JSON 数组
                List<int> cidList;

                // 方法1：使用 JArray.Parse
                var jArray = JArray.Parse(permissionsJson);
                cidList = jArray.Select(token => token.Value<int>()).ToList();

                if (cidList == null || !cidList.Any())
                    return Enumerable.Empty<DataSourcesDto>();

                // 3. 根据 cid 列表查询 SEBI_DataSources 表
                var query = "SELECT cid,cAccName FROM SEBI_DataSources WHERE cid IN @CidList and State = 1";
                var dataSources = await connection.QueryAsync<DataSourcesDto>(query, new { CidList = cidList });

                return dataSources;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取所有SEBI_Operator记录异常");
                return Enumerable.Empty<DataSourcesDto>();
            }
            finally
            {
                await connection.CloseAsync();
            }
        }
        public async Task<BIDBContentDto> GetDBContentAsync(int cid)
        {
            using var connection = new SqlConnection(_connectionString);
            await connection.OpenAsync();

            try
            {
                var result = await connection.QueryFirstOrDefaultAsync<BIDBContentDto>(
                    @"SELECT cid, cIP, cDBName, cDBUser, cDBPassword
                      FROM SEBI_DataSources 
                      WHERE cid = @cid",
                    new { cid }
                );
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据cid[{0}]查询SEBI_DataSources异常", cid);
                return null;
            }
            finally
            {
                await connection.CloseAsync();
            }
        }
    }
}
